


function langString(str){
	document.write(window[str]);
}

var sombraGmailer = new Class({
	l: "sombraGmailerAJAX.php",
	init: function(){},
	connect: function(user,pass){
		user = user.toLowerCase().replace("@gmail.com","")+"@gmail.com";
		$_('loginPageInputs',{".display":"none"});
		$_('loginPageLoading',{".display":"inline"}).$T("SPAN")[0].innerHTML = user;

		var params = "command=connect&account="+user+"&password="+pass;
		ajaxPetition(this.l,params,function(ajax){
			var r = eval("("+ajax.responseText+")");
			if(parseInt(r.errorCode)>0){$_("loginPageLoadingErrors",{innerHTML:"Error "+r.errorCode+": "+r.errorDescription});return;}
			//FIXME: buscar método genérico
			$_("gmailAccount",{innerHTML:user});
			$_("loginPage",{".display":"none"});

			var h = $_("boxContainer").empty();
			$A(r.data.box).each(function(elem){this.renderBox(h,elem);}.bind(this));
			sombraGmailer_panelOp("inbox");
		}.bind(this));
	},
	renderBox: function(h,box){
		function selectBox(boxTD){
			boxTD.className = (boxTD.className=="mailUnselectedTd") ? "mailSelectedTd" : "mailUnselectedTd";
			$fix(boxTD).$T("INPUT")[0].checked = (boxTD.className=="mailUnselectedTd") ? "" : "checked";
		}

		function starSwitch(isStarred,boxID,ths){
			ths.boxAction((isStarred == "yes") ? "removestar" : "addstar",boxID);
			return (isStarred == "yes") ? "no" : "yes";
		}

		var tr = $C("TR",{className:"mailReaded_"+box.isReaded},h);
		var ch = $C("TD",{className:"mailUnselectedTd",onclick:function(){selectBox(ch);}},tr);
		$C("INPUT",{type:"checkbox",className:"f",value:box.boxId+""},ch);
		var sd = $C("TD",{className:"mailStarred_"+box.isStarred,onclick:function(){sd.className = "mailStarred_"+starSwitch(box.isStarred,box.boxId,this);}.bind(this)},tr);
		var td = $C("TD",{".whiteSpace":"nowrap",innerHTML:box.boxSender+""},tr);
		var td = $C("TD",{className:"mailSnippet paperclip_"+box.haveAttachment},tr);
		$C("DIV",{innerHTML:"<nobr>"+box.boxLabels+"</nobr><nobr>"+box.boxLabels+"</nobr>"+box.boxTitle+" - "+box.boxSnippet,onclick:function(){this.openBox(box,tr);}.bind(this)},td);
		var td = $C("TD",{className:"boxDateTD",innerHTML:box.boxDate+""},tr);
	},
	getBox: function(boxType,st,label){
		var params = "command=getInbox&boxType="+boxType;
		if(st){params += "&st="+st;}
		if(label){params += "&label="+label;}
		ajaxPetition(this.l,params,function(ajax){
			var r = eval("("+ajax.responseText+")");if(parseInt(r.errorCode)>0){alert(print_r(r));return;}

			var h = $_("boxContainer").empty();
			$A(r.data.box).each(function(elem){this.renderBox(h,elem);}.bind(this));
			sombraGmailer_panelOp("inbox");
		}.bind(this));
	},
	openBox: function(box,row){
		var params = "command=openBox&boxId="+box.boxId;
		ajaxPetition(this.l,params,function(ajax){
			var r = eval("("+ajax.responseText+")");if(parseInt(r.errorCode)>0){alert(print_r(r));return;}
			alert(print_r(r));
			//alert(ajax.responseText);
			row.className = "mailReaded_yes";
		});
	},
	multipleBoxAction: function(boxAction,label){
		var h = $_("boxContainer");
		var selected = [];
		$A($_("boxContainer").$T("INPUT")).each(function(elem){if(elem.checked){selected.push(elem.value);}});
		this.boxAction(boxAction,selected,label);
	},
	boxAction: function(boxAction,boxId,label){
		var params = "command=boxAction&boxAction="+boxAction+"&boxId="+boxId;
		if(label){params += "&label="+label;}
		ajaxPetition(this.l,params,function(ajax){
			var r = eval("("+ajax.responseText+")");if(parseInt(r.errorCode)>0){alert(print_r(r));return;}

			var h = $_("boxContainer").empty();
			$A(r.data.box).each(function(elem){this.renderBox(h,elem);}.bind(this));
		}.bind(this));
	},
	processResponse: function(xml){
		if(xml.$T("box").length>0){$('boxContainer').innerHTML = "";}
		$A(xml.$T("box")).each(function(elem){
			var row = new Object();
			$A(elem.$T("*")).each(function(el){row[el.tagName] = elem.tagValue(el.tagName);});
			sombraGmailer_addBox(row);
		});

		if(xml.$T("label").length>0){$('labelContainer').innerHTML = "";}
		$A(xml.$T("label")).each(function(elem){
			sombraGmailer_addLabel(elem.tagValue("name"),elem.tagValue("link"));
		});

		var pager = new Object();
		$A(xml.$T("pagers")[0].$T("*")).each(function(elem){
			if(elem.firstChild){pager[elem.tagName] = elem.firstChild.nodeValue;}
		});
		this.addPager(pager);
	},
	addPager: function(p){
		h = $('selectionMenuPagerTop');
		h.innerHTML = "";
		p["currentTop"] += " "+lang_gmailPagerOf+" ";
		p["currentBottom"] += " - ";
		for(var a in p){
			switch(a){
				case "first":
				case "previous":
				case "next":
				case "last":
					var node = sombraGmailer_addPagerHelper(p[a]);
					var s = document.createElement("SPAN");
					s.onclick = function(){this.getBox(node.boxType,node.st,node.label);}.bind(this);
					s.innerHTML = lang_gmailPagerFirst
					h.appendChild(s);
					break;
				case "currentBottom":
				case "currentTop":
				case "total":
					h.appendChild(document.createTextNode(p[a]));
					break;
			}
		}
	},
	signOut: function(){
		ajaxPetition(this.l,"command=signOut",function(ajax){
			var r = eval("("+ajax.responseText+")");if(parseInt(r.errorCode)>0){alert(print_r(r));return;}
			window.location.reload();
		});
	}
});

var s = new sombraGmailer();
window.onload = function(){
	if(cookieTake("gmailerUser")){
		$_("loginPage",{".display":"none"});
		s.getBox("INBOX");
		return;
	}
	//s.connect("darksoldiermail","soldiermailer");
}

function sombraGmailer_connect(){
	var user = $_("loginName").value;
	var pass = $_("loginPass").value;
	s.connect(user,pass);
}


function moreActionSwitch(){
	if(document.getElementById('menuActions').style.visibility=='visible'){
		document.getElementById('menuActions').style.visibility='hidden';
	}else{
		document.getElementById('menuActions').style.visibility='visible';
	}
}

function sombraGmailer_panelOp(boxType){

	var h = $_("panelOpHolderTop").empty();
	$C("DIV",{className:"panelButton",innerHTML:"Archive",onclick:function(){s.multipleBoxAction('archive');}},h);
	$C("DIV",{className:"panelButton",innerHTML:"Report Spam",onclick:function(){s.multipleBoxAction('reportspam');}},h);
	$C("DIV",{className:"panelButton",innerHTML:"Delete",onclick:function(){s.multipleBoxAction('delete');}},h);

return;
	var code="";
	switch(boxType){
		case "inbox":
			code += "<div class=\"panelButton\" onclick=\"sombraGmailer_multipleBoxActions('archive');\">" + lang_gmailPanelOpArchive + "</div>\n";
			code += "<div class=\"panelButton\" onclick=\"sombraGmailer_multipleBoxActions('reportspam');\">" + lang_gmailPanelOpReportSpam + "</div>\n";
			code += "<div class=\"panelButton\" onclick=\"sombraGmailer_multipleBoxActions('delete');\">" + lang_gmailPanelOpDelete + "</div>\n";
			code += "<div class=\"panelButton\" onclick=\"moreActionSwitch();\">" + lang_gmailPanelOpMore + "</div>\n";
			code += "<span onclick=\"alert(1);\">" + lang_gmailPanelOpUpdate + "</span>\n";
		break;
		case "starred":
			//FIXME: eliminar estrella, lang
			code += "<div class=\"panelButton\" onclick=\"sombraGmailer_multipleBoxActions('removestar');\">Eliminar estrella</div>\n";
			code += "<div class=\"panelButton\" onclick=\"sombraGmailer_multipleBoxActions('reportspam');\">" + lang_gmailPanelOpReportSpam + "</div>\n";
			code += "<div class=\"panelButton\" onclick=\"sombraGmailer_multipleBoxActions('delete');\">" + lang_gmailPanelOpDelete + "</div>\n";
			code += "<div class=\"panelButton\" onclick=\"moreActionSwitch();\">" + lang_gmailPanelOpMore + "</div>\n";
			code += "<span onclick=\"alert(1);\">" + lang_gmailPanelOpUpdate + "</span>\n";
		break;
		case "sentmail":
			code += "<div class=\"panelButton\" onclick=\"sombraGmailer_multipleBoxActions('delete');\">" + lang_gmailPanelOpDelete + "</div>\n";
			code += "<div class=\"panelButton\" onclick=\"moreActionSwitch();\">" + lang_gmailPanelOpMore + "</div>\n";
			code += "<span onclick=\"alert(1);\">" + lang_gmailPanelOpUpdate + "</span>\n";
		break;
		case "drafts":
			//FIXME: Descartar Borradores, lang
			code += "<div class=\"panelButton\" onclick=\"sombraGmailer_multipleBoxActions('delete');\">Descartar Borradores</div>\n";
			code += "<div class=\"panelButton\" onclick=\"moreActionSwitch();\">" + lang_gmailPanelOpMore + "</div>\n";
			code += "<span onclick=\"alert(1);\">" + lang_gmailPanelOpUpdate + "</span>\n";
		break;
		case "allmail":
			//FIXME: Descartar Borradores, lang
			code += "<div class=\"panelButton\" onclick=\"alert(1);\">Mover a Recibidos</div>\n";
			code += "<div class=\"panelButton\" onclick=\"sombraGmailer_multipleBoxActions('reportspam');\">" + lang_gmailPanelOpReportSpam + "</div>\n";
			code += "<div class=\"panelButton\" onclick=\"moreActionSwitch();\">" + lang_gmailPanelOpMore + "</div>\n";
			code += "<span onclick=\"alert(1);\">" + lang_gmailPanelOpUpdate + "</span>\n";
		break;
		case "spam":
			//FIXME: Descartar Borradores, lang
			code += "<div class=\"panelButton\" onclick=\"alert(1);\">Suprimir definitivamente</div>\n";
			code += "<div class=\"panelButton\" onclick=\"alert(1);\">No es spam</div>\n";
			code += "<div class=\"panelButton\" onclick=\"moreActionSwitch();\">" + lang_gmailPanelOpMore + "</div>\n";
			code += "<span onclick=\"alert(1);\">" + lang_gmailPanelOpUpdate + "</span>\n";
		break;
		case "trash":
			//FIXME: Descartar Borradores, lang
			code += "<div class=\"panelButton\" onclick=\"alert(1);\">Suprimir definitivamente</div>\n";
			code += "<div class=\"panelButton\" onclick=\"alert(1);\">Mover a Recibidos</div>\n";
			code += "<div class=\"panelButton\" onclick=\"moreActionSwitch();\">" + lang_gmailPanelOpMore + "</div>\n";
			code += "<span onclick=\"alert(1);\">" + lang_gmailPanelOpUpdate + "</span>\n";
		break;
	}

	
	document.getElementById('panelOpHolderTop').innerHTML = code;
	document.getElementById('panelOpHolderBottom').innerHTML = code;
}

function sombraGmailer_addLabel(labelName,labelLink){
	var code = "<div onclick='s.getBox(\"label\",0,\""+labelLink+"\");'>"+labelName+"</div>";
	document.getElementById('labelContainer').innerHTML += code;

	var action = "<tr><td class='elementAction'>"+labelName+"</td><td> | <span onclick='sombraGmailer_multipleBoxActions(\"applylabel\",\""+labelLink+"\");'>A&ntilde;adir</span> &bull; <span onclick='sombraGmailer_multipleBoxActions(\"removelabel\",\""+labelLink+"\");'>Eliminar</span></td></tr>\n";
	document.getElementById('labelActions').innerHTML += action;
}

function sombraGmailer_addConv(isStarred,convSender,convSenderMail,haveAttachment,convDate,convReplyTo,convTo,body,attachments){
	//alert(attachments.length);
	code ='<tr><td>\n';
	code +='	<div style="background:white;">\n';
	code +='		<div style="height:18; padding-top:4; padding-right:4;"><div style="float:left;"><span style="background:URL(images/estar.png) center no-repeat; padding-right:24; padding-top:10; padding-bottom:10;"></span><nobr><span style="font-weight:bold; color:#434a54; font-size:11;">'+convSender+'</span> <span>'+convSenderMail+'</span></nobr></div><div style="float:right;">'+convDate+'</div></div>\n';
	code +='		<div style="background:#304558 URL(images/degradado1.png) repeat-x; padding:4; border:1px solid #304558; color:white;">\n';
	code +='			<div><b>Responder a:</b> '+convReplyTo+'</div>\n';
	code +='			<div><b>Para:</b> '+convTo+' </div>\n';
	code +='			<div>Responder | Responder a todos | Reenviar | Imprimir | Suprimir | Mostrar original</div>\n';
	code +='		</div>\n';
	if(haveAttachment=="yes"){
		code +='	<div style="font-size:12; height:40;">\n';
		for(var a=0;a<attachments.length;a++){
			code +='	<div onclick="sombraGmailer_downloadAttachment(\'' + attachments[a].attachmentName + '\',\'' + attachments[a].attachmentLink + '\');" title="' + attachments[a].attachmentName + '" style="cursor:pointer; float:right; background:URL(images/mimetypes/' + attachments[a].attachmentType + '.png) center; width:38; height:40;"></div>\n';
		}
		code +='	</div>\n';
	}
	code +='		<div style="font-size:12; padding:4; padding-top:0; border-bottom:2px dotted #566069;">'+body+'</div>\n';
	code +='	</div>\n';
	code +='</td></tr>\n';

	document.getElementById('boxContainer').innerHTML += code;
}
function sombraGmailer_downloadAttachment(fileName,link){
	link=link.split('?');
	link=link[link.length-1];

	if(!document.getElementById('downloadAttachmentHelper')){
		document.getElementsByTagName('body')[0].innerHTML += "<iframe id='downloadAttachmentHelper' src='sombraGmailer.php?command=getAttachment&fileName="+fileName+"&"+link+"'>";
	}else{
		document.getElementById('downloadAttachmentHelper').src="sombraGmailer.php?command=getAttachment&fileName="+fileName+"&"+link;
	}
}
function sombraGmailer_addPager(first,previous,currentBottom,currentTop,total,next,last){
	var node;

	code = '';
	if(first != ""){node = sombraGmailer_addPagerHelper(first); code += ' <span onclick="sombraGmailer_getInbox(\''+node.boxType+'\',\''+node.st+'\',\''+node.label+'\');">'+lang_gmailPagerFirst+' </span>';}
	if(previous != ""){node = sombraGmailer_addPagerHelper(previous); code += ' <span onclick="sombraGmailer_getInbox(\''+node.boxType+'\',\''+node.st+'\',\''+node.label+'\');">'+lang_gmailPagerPrevious+' </span>';}
	code += currentBottom+' - '+currentTop+' '+lang_gmailPagerOf+' '+total;
	if(next != ""){node = sombraGmailer_addPagerHelper(next); code += ' <span onclick="sombraGmailer_getInbox(\''+node.boxType+'\',\''+node.st+'\',\''+node.label+'\');"> '+lang_gmailPagerNext+'</span>';}
	if(last != ""){node = sombraGmailer_addPagerHelper(last); code += ' <span onclick="sombraGmailer_getInbox(\''+node.boxType+'\',\''+node.st+'\',\''+node.label+'\');"> '+lang_gmailPagerLast+'</span>';}

	document.getElementById('selectionMenuPagerTop').innerHTML = code;
}
function sombraGmailer_addPagerHelper(str){
	var brokenString = str.split('&');
	if(!brokenString[1]){brokenString[1]="";}
	if(!brokenString[2]){brokenString[2]="";}
	var node = new Object();

	if(brokenString[0].substring(0,3)=="?st" || brokenString[0]=="?"){
		node.boxType = "INBOX";
		node.st = brokenString[0].replace("?st=","");
		node.label = "";
		return node;
	}
	if(brokenString[0]=="?s=l"){
		node.boxType = "LABEL";
		node.label = brokenString[1].replace("l=","");
		node.st = brokenString[2].replace("st=","");
		return node;
	}
	node.boxType = brokenString[0].replace("?s=r","STARRED").replace("?s=s","SENTMAIL").replace("?s=d","DRAFTS").replace("?s=a","ALLMAIL").replace("?s=m","SPAM").replace("?s=t","TRASH");
	node.st = brokenString[1].replace("st=","");
	node.label = "";
	return node;
}
function composeShow(){
	var code = '<tr style="background:#fff5c2;"><td colspan="2" style="height:10;"></td></tr>\n';
	code += '<tr style="background:#fff5c2;"><td style="padding:10; text-align:center; vertical-align:top;">Para:</td><td style="width:100%;"><textarea style="width:100%;"></textarea></td></tr>\n';
	code += '<tr style="background:#fff5c2;"><td style="padding:10; text-align:center; vertical-align:top;">CC:</td><td><input style="width:100%; visibility:visible;"></td></tr>\n';
	code += '<tr style="background:#fff5c2;"><td style="padding:10; text-align:center; vertical-align:top;">CCO:</td><td><input style="width:100%; visibility:visible;"></td></tr>';
	code += '<tr style="background:#fff5c2;"><td style="padding:10; text-align:center; vertical-align:top;">Asunto:</td><td><input style="width:100%; visibility:visible;"></td></tr>\n';
	code += '<tr style="background:#fff5c2;"><td style="padding:10; text-align:center; vertical-align:top;"></td><td><textarea style="width:100%; height:300;"></textarea></td></tr>\n';
	code += '<tr style="background:#fff5c2;"><td colspan="2" style="height:10;"></td></tr>\n';

	document.getElementById('boxContainer').innerHTML = code;
	document.getElementById('selectionMenuTop').style.display="none";
	document.getElementById('selectionMenuBottom').style.display="none";
}
